<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolBar" style="float:left;padding-top: 10px;padding-left: 50px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-search"
                     :label="$t('action.search')"
                     perms="basic:user:view"
                     @click="findPage"/>
        </el-form-item>
        <el-form-item>
          <kt-button type="primary"
                     icon="fa fa-plus"
                     :label="$t('action.add')"
                     perms="basic:user:add"
                     @click="showAdd"/>
        </el-form-item>
      </el-form>
    </div>
    <div class="toolBar" style="float:right;padding-top: 10px;padding-left: 15px;">
      <el-form :inline="true" :size="size">
        <el-form-item>
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o"></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog ref="tableColumnFilterDialog"
                                  :columns="columns"
                                  @handleFilterColumns="handleFilterColumns">
      </table-column-filter-dialog>
    </div>

    <!--表格内容栏-->
    <kt-table perms-edit="basic:user:edit"
              perms-delete="basic:user:delete"
              :data="pageResult"
              :columns="filterColumns"
              @findPage="findPage"
              @handleEdit="showEdit"
              @handleDelete="handleDelete">
    </kt-table>

    <!--新增编辑界面-->
    <el-dialog width="25%"
               :title="operation?'新增':'编辑'"
               :visible.sync="dialogVisible"
               :close-on-click-modal="false">
      <el-form :model="dataForm"
               label-width="80px"
               :rules="dataFormRules"
               ref="dataForm"
               :size="size"
               label-position="right">
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="false"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input v-model="dataForm.name" auto-complete="false"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="deptName">
          <popup-tree-input :data="deptData"
                            :props="deptTreeProps"
                            :prop="dataForm.deptName"
                            :node-key="'' + dataForm.deptId"
                            :current-change-handle="deptTreeCurrentChangeHandle">
          </popup-tree-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="dataForm.email" auto-complete="false"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="dataForm.mobile" auto-complete="false"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="userRoles">
          <el-select v-model="dataForm.userRoles"
                     :clearable="true"
                     multiple
                     placeholder="请选择角色"
                     style="width: 100%">
            <el-option v-for="item in roles"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="授权店铺" prop="authorizedShops">
          <el-select v-model="dataForm.authorizedShops"
                     :clearable="true"
                     multiple
                     placeholder="请选择店铺"
                     style="width: 100%">
            <el-option v-for="item in shopList"
                       :key="item"
                       :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button :size="size" @click.native="dialogVisible=false">{{$t('action.cancel')}}</el-button>
        <el-button :size="size" type="primary" :loading="editLoading" @click.native="submitForm">
          {{$t('action.submit')}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import KtTable from '../core/KtTable'
  import KtButton from '../core/KtButton'
  import {format} from "../../utils/datetime";
  import TableColumnFilterDialog from '../core/TableColumnFilterDialog'
  import PopupTreeInput from '../../components/PopupTreeInput/index'

  export default {
    name: 'User',
    components: {
      KtButton,
      KtTable,
      PopupTreeInput,
      TableColumnFilterDialog
    },
    data() {
      return {
        size: 'small',
        filters: {
          name: ''
        },
        columns: [],
        filterColumns: [],
        pageRequest: {},
        pageResult: {},
        operation: false,//true新增 false编辑
        dialogVisible: false,//新增编辑界面是否显示
        editLoading: false,
        dataFormRules: {
          name: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
          ]
        },
        //新增或编辑页面
        dataForm: {
          id: 0,
          name: '',
          password: '',
          deptId: 1,
          deptName: '',
          email: '',
          mobile: '',
          status: 1,
          userRoles: [],
          authorizedShops: []
        },
        deptData: [],
        deptTreeProps: {
          label: 'name',
          children: 'children'
        },
        roles: [],
        shopList: []
      }
    },
    methods: {
      //获取分页数据
      findPage(data) {
        if ((data !== null && typeof data !== 'undefined') && typeof data.pageRequest !== 'undefined') {
          this.pageRequest = data.pageRequest;
        }
        this.pageRequest.params = {name: this.filters.name};
        this.$api.user.findPage(this.pageRequest).then((res) => {
          if (res.code === 200) {
            this.pageResult = res.data;
            this.convertDeptNameAndRoleName(this.pageResult, this.deptData, this.roles);
          } else {
            this.$message({message: res.message, type: 'error'});
          }
        }).then((data !== null && typeof data !== 'undefined') ? data.callback : '')
      },
      //处理部门和角色显示
      convertDeptNameAndRoleName(pageResult, deptData, roles) {
        let userList = pageResult.content;
        for (let i = 0, len = userList.length; i < len; i++) {
          let user = userList[i];
          deptData.forEach(e => {
            if (user.deptId === e.id) {
              user.deptName = e.name;
            }
          });
          let roleNames = [];
          let roleList = user.userRoles;
          for (let a = 0, aLen = roleList.length; a < aLen; a++) {
            roles.forEach(r => {
              if (roleList[a].roleId === r.id) {
                if (a < aLen - 1) {
                  roleNames.push(r.name + ', ');
                } else {
                  roleNames.push(r.name);
                }
              }
            });
          }
          user.roleNames = roleNames;
          user.statusDesc = user.status === 1 ? '启用' : '禁用';
          user.authorizedShopStr = user.authorizedShops.join(' | ');

        }
      },
      //加载用户角色
      findUserRoles() {
        this.$api.role.findAll().then((res) => {
          this.roles = res.data;
        })
      },
      //加载当前用户拥有授权的店铺
      findShopList() {
        this.shopList = localStorage.getItem('authorizedShops').split(',');
      },
      //批量删除
      handleDelete(data) {
        this.$api.user.batchDelete(data.params).then(data !== null ? data.callback : '');
      },
      //显示新增界面
      showAdd() {
        this.dialogVisible = true;
        this.operation = true;
      },
      //显示编辑界面
      showEdit(params) {
        this.dialogVisible = true;
        this.operation = false;
        this.dataForm = Object.assign({}, params.row);
        let userRoles = [];
        for (let i = 0, len = params.row.userRoles.length; i < len; i++) {
          userRoles.push(params.row.userRoles[i].roleId);
        }
        this.dataForm.userRoles = userRoles;
      },
      //编辑
      submitForm() {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗?', '提示', {}).then(() => {
              this.editLoading = true;
              let params = Object.assign({}, this.dataForm);
              let userRoles = [];
              for (let i = 0, len = params.userRoles.length; i < len; i++) {
                let userRole = {
                  userId: params.id,
                  roleId: params.userRoles[i]
                };
                userRoles.push(userRole);
              }
              params.userRoles = userRoles;
              this.$api.user.save(params).then((res) => {
                this.editLoading = false;
                if (res.code === 200) {
                  this.$message({message: '保存成功', type: 'success'});
                  this.dialogVisible = false;
                  this.$refs['dataForm'].resetFields();
                } else {
                  this.$message({message: res.message, type: 'error'});
                }
                this.findPage();
              })
            });
          }
        })
      },
      //获取部门列表
      findDeptTree() {
        this.$api.dept.findTree().then((res) => {
          this.deptData = res.data;
        })
      },
      //菜单树选中
      deptTreeCurrentChangeHandle(data, node) {
        this.dataForm.deptId = data.id;
        this.dataForm.deptName = data.name;
      },
      //时间格式化
      dateFormat(row, column, cellVal, index) {
        return format(row[column.property])
      },
      //处理表格列过滤显示
      displayFilterColumnDialog() {
        this.$refs.tableColumnFilterDialog.setDialogVisible(true);
      },
      // 处理表格列过滤显示
      handleFilterColumns(data) {
        this.filterColumns = data.filterColumns;
        this.$refs.tableColumnFilterDialog.setDialogVisible(false);
      },
      // 处理表格列过滤显示
      initColumns() {
        this.columns = [
         // {prop: "id", label: "ID", minWidth: 50},
          {prop: "name", label: "用户名", minWidth: 100},
          {prop: "deptName", label: "部门", minWidth: 100},
          {prop: "roleNames", label: "角色", minWidth: 100},
          {prop: "email", label: "邮箱", showOverflow: true, minWidth: 150},
          {prop: "mobile", label: "手机", minWidth: 150},
          {prop: "statusDesc", label: "状态", minWidth: 70},
          {prop: "authorizedShopStr", label: "授权店铺", showOverflow: true, minWidth: 200},
        ];
        this.filterColumns = JSON.parse(JSON.stringify(this.columns));
      }
    },
    mounted() {
      this.findDeptTree();
      this.findUserRoles();
      this.initColumns();
      this.findShopList();
    }
  }
</script>

<style scoped>

</style>
